<template>
  <!-- 添加或修改设备模板对话框 -->
  <el-dialog
    :title="title"
    :visible.sync="open"
    append-to-body
    :modal="false"
    top="74px"
    class="container-dailog transition-box"
    @close="cancel"
    :class="$store.state.app.sidebar.opened ? 'openSidebar' : 'hideSidebar'"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <div class="border padding-lr-20 padding-top-20">
        <div class="text-12">模板信息</div>
        <div class="flex margin-top-10">
          <div>
            <el-form-item label="模板名称" prop="templatesName">
              <el-input v-model="form.templatesName" placeholder="请输入模板名称" />
            </el-form-item>
            <el-form-item label="所属组织" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择所属组织"
              />
            </el-form-item>
            <el-form-item label="采集方式" prop="acquisitionMethod">
              <el-radio-group v-model="form.acquisitionMethod">
                <el-radio
                  v-for="dict in dict.type.acquisition_method"
                  :key="dict.value"
                  :label="dict.raw.dictCode"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="通信协议" prop="protocol">
              <el-select v-model="form.protocol" placeholder="通信协议">
                <el-option
                  v-for="dict in dict.type.communication_protocol"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.raw.dictCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="判断方式" prop="statusConfig">
              <el-radio-group v-model="form.statusConfig">
                <el-radio
                  v-for="dict in dict.type.status_config"
                  :key="dict.value"
                  :label="dict.raw.dictCode"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
      </div>
      <div class="border padding-lr-20 padding-top-20 margin-top-20">
        <div class="text-12 flex justify-between align-center">
          变量列表
        </div>
        <div class="margin-top-10">
          <!-- <el-form-item label="协议和产品" prop="templatesName">
            <div class="flex">
              <treeselect
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择协议和产品"
              />
            </div>
          </el-form-item> -->
        </div>
        <div class="flex margin-bottom-20 justify-between">
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button
                type="primary"
                size="small"
                @click="addVarHandle"
                >添加变量</el-button
              >
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button
                type="primary"
                size="small"
                >导入变量</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                size="small"
                >排序</el-button
              >
            </el-col> -->
          </el-row>
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-select v-model="value" placeholder="请选择变量类型"> 
                <el-option
                  v-for="dict in dict.type.variable_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-col>
            <el-col :span="1.5">
              <el-input
                placeholder="请输入变量名称"
                clearable
              />
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                size="small"
                >查询</el-button
              >
            </el-col>
          </el-row>
        </div>
        <div class="margin-top-20">
          <el-table height="300px" :data="valList">
            <el-table-column label="序号" type="index" />
            <el-table-column label="变量名称" prop="variableName" align="center" />
            <el-table-column label="变量类型" prop="variableTypeName" align="center" />
            <el-table-column label="数值类型" prop="numberFormatName" align="center"/>
            <el-table-column label="读写" prop="readWriteWayName" align="center" />
            <el-table-column label="存储方式" prop="storageMethodName" align="center" />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleVariableUpdate(scope.row)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleVariableDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-form>
    <!-- <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div> -->
    <el-dialog :title="variableTitle" :visible.sync="variableOpen" width="800px" append-to-body>
      <el-form :disabled="variableDisabled" :rules="varrules" label-position="right" ref="formVariable" :model="formVariable" label-width="100px">
        <div class="flex">
          <el-form-item label="变量名称" class="flex-1" prop="variableName">
            <el-input v-model="formVariable.variableName" placeholder="请输入变量名称"></el-input>
          </el-form-item>
          <el-form-item label="变量单位" class="flex-1 margin-left-20" prop="variableUnit">
            <el-input v-model="formVariable.variableUnit" placeholder="请输入变量单位"></el-input>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="变量类型" class="flex-1" prop="variableType">
            <el-select v-model="formVariable.variableType" placeholder="请选择变量类型"> 
              <el-option
                v-for="dict in dict.type.variable_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.raw.dictCode"
              />
            </el-select>
          </el-form-item>
        </div>
        <!-- <div class="flex">
          <el-form-item label="变量标识符" class="flex-1">
            <el-input></el-input>
          </el-form-item>
        </div> -->
        <div class="flex">
          <el-form-item label="寄存器" class="flex-1" prop="storage">
            <div class="flex">
              <el-select v-model="formVariable.storage" placeholder=""> 
                <el-option
                  v-for="dict in dict.type.storage"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.raw.dictCode"
                />
              </el-select>
              <el-input style="width: 200px;" class="margin-left-10" v-model="formVariable.serialNum" placeholder=""></el-input>
            </div>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="数据格式" class="flex-1" prop="dataFormat">
            <el-select v-model="formVariable.dataFormat" placeholder="请选择数据格式"> 
              <el-option
                v-for="dict in dict.type.data_format"
                :key="dict.value"
                :label="dict.label"
                :value="dict.raw.dictCode"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="采集频率" class="flex-1" prop="acquisitionFrequency">
            <el-select v-model="formVariable.acquisitionFrequency" placeholder="请选择数字格式"> 
              <el-option
                v-for="dict in dict.type.acquisition_frequency"
                :key="dict.value"
                :label="dict.label"
                :value="dict.raw.dictCode"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="数字格式" class="flex-1" prop="numberFormat">
            <el-select v-model="formVariable.numberFormat" placeholder="请选择数字格式"> 
              <el-option
                v-for="dict in dict.type.number_format"
                :key="dict.value"
                :label="dict.label"
                :value="dict.raw.dictCode"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="存储方式" class="flex-1" prop="storageMethod">
            <el-select v-model="formVariable.storageMethod" placeholder="请选择存储方式"> 
              <el-option
                v-for="dict in dict.type.storage_method"
                :key="dict.value"
                :label="dict.label"
                :value="dict.raw.dictCode"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="读写方式" class="flex-1" prop="readWriteWay">
            <el-select v-model="formVariable.readWriteWay" placeholder="请选择读写方式"> 
              <el-option
                v-for="dict in dict.type.read_write_way"
                :key="dict.value"
                :label="dict.label"
                :value="dict.raw.dictCode"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="展现形式" class="flex-1" prop="showData">
            <el-select v-model="formVariable.showData" placeholder="请选择展现形式"> 
              <el-option
                v-for="dict in dict.type.show_data"
                :key="dict.value"
                :label="dict.label"
                :value="dict.raw.dictCode"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="flex">
          <el-form-item label="是否展示" class="flex-1" prop="userOpen">
            <el-select v-model="formVariable.userOpen" placeholder="请选择是否展示给用户"> 
              <el-option
                v-for="dict in dict.type.user_open"
                :key="dict.value"
                :label="dict.label"
                :value="dict.raw.dictCode"
              />
            </el-select>
          </el-form-item>
        </div>
        <!-- <div class="flex">
          <el-form-item label="采集公式" class="flex-1" prop="acquisitionFormula">
            <el-input v-model="form.acquisitionFormula"></el-input>
          </el-form-item>
        </div> -->
        <!-- <div class="flex">
          <el-form-item label="控制公式" class="flex-1">
            <el-input></el-input>
          </el-form-item>
        </div> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="varCancel">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { addTemplates, updateTemplates } from "@/api/iot/templates";
  import { addVariable, delVariable, updateVariable } from "@/api/iot/variable";
  import { listTempVariable } from "@/api/iot/device";

  export default {
    name: "TemplatesForm",
    dicts: ["acquisition_method", "status_config", "variable_type", "acquisition_frequency", "read_write_way", "storage_method", "number_format", "data_format","storage","show_data","user_open","communication_protocol"],
    components: { Treeselect },
    props: {
      supThis: {
        type: Object,
        default: null,
      },
      deptOptions: {
        type: Array,
        default: () => [],
      }
    },
    data() {
      return {
        type: '',
        value: '',
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        variableOpen: false,
        // 表单参数
        form: {},
        // 表单变量参数
        formVariable: {},
        // 表单校验
        rules: {
          templatesName: [
            { required: true, message: "模板名称不能为空", trigger: "blur" },
          ],
          deptId: [
            { required: true, message: "所属组织id不能为空", trigger: "blur" },
          ],
          acquisitionMethod: [
            { required: true, message: "采集方式必选", trigger: "blur" },
          ],
          // protocol: [
          //   { required: true, message: "通信协议必选", trigger: "blur" },
          // ],
          statusConfig: [
            { required: true, message: "判断方式必选", trigger: "blur" },
          ],
        },
        varrules: {
          variableName: [
            { required: true, message: "变量名称不能为空", trigger: "blur" },
          ],
          variableType: [
            { required: true, message: "变量类型不能为空", trigger: "blur" },
          ],
          dataFormat: [
            { required: true, message: "数据格式必选", trigger: "blur" },
          ],
          numberFormat: [
            { required: true, message: "数字格式必选", trigger: "blur" },
          ],
          storageMethod: [
            { required: true, message: "存储方式必选", trigger: "blur" },
          ],
          readWriteWay: [
            { required: true, message: "读写方式必选", trigger: "blur" },
          ],
          showData: [
            { required: true, message: "展现形式必选", trigger: "blur" },
          ],
          userOpen: [
            { required: true, message: "是否展示必选", trigger: "blur" },
          ],
        },
        varObject: {
          open: false,
          form: {},
          rules: {},
        },
        valList: [],
        addIsSave: false,
        variableDisabled: false,
        variableTitle: ''
      }
    },
    methods: {
      // 表单重置
      reset() {
        this.form = {
          id: null,
          templatesName: null,
          deptId: null,
          acquisitionMethod: this.dict.type.acquisition_method[0].raw.dictCode,
          statusConfig: this.dict.type.status_config[0].raw.dictCode,
          protocol: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
        };
        this.resetForm("form");
      },
      // 查询变量列表
      varListQueryHandle() {
        listTempVariable({
          deviceTemplateId: this.form.id,
        }).then((response) => {
          this.valList = response.rows
        });
      },
      addVarHandle() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.variableTitle = '新增变量'
            this.submitTempForm();
            this.variableOpen = true
          }
        })
      },
      // 修改变量
      handleVariableUpdate(row) {
        this.variableTitle = '修改变量'
        this.variableOpen = true
        this.formVariable = row
      },
      // 删除变量
      handleVariableDelete(row) {
        const ids = row.id;
        this.$modal
          .confirm('是否确认删除模板变量编号为"' + ids + '"的数据项？')
          .then(function () {
            return delVariable(ids);
          })
          .then(() => {
            this.varListQueryHandle()
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      },
      /** 提交按钮 */
      submitForm() {
        if(this.form.id==null || this.form.id==''){
          this.$modal.msgSuccess("需新增模板数据");
          return false;
        }
        this.$refs["formVariable"].validate((valid) => {
          this.formVariable.deviceTemplateId = this.form.id
          if (valid) {
            if (this.formVariable.id != null) {
              updateVariable(this.formVariable).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.variableOpen = false;
                this.varListQueryHandle()
                // this.supThis.getList();
              });
            } else {
              addVariable(this.formVariable).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.varListQueryHandle()
                this.variableOpen = false;
                // this.supThis.getList();
              });
            }
          }
        });
      },

      /** 提交模版数据 */
      submitTempForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              updateTemplates(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                // this.reset();
                // this.open = false;
                this.supThis.getList();
              });
            } else {
              addTemplates(this.form).then((response) => {
                this.form = response.data
                this.$modal.msgSuccess("新增成功");
                // this.reset();
                // this.open = false;
                this.supThis.getList();
              });
            }
          }
        });
      },
      // 取消按钮
      cancel() {
        // this.valList = []
        this.type = ''
        // this.reset();
      },
      varCancel() {
        this.formVariable = {
          variableName: null,
          variableUnit: null,
          variableType: null,
          storage: null,
          dataFormat: null,
          acquisitionFrequency: null,
          numberFormat: null,
          storageMethod: null,
          readWriteWay: null,
          showData: null,
          userOpen: null,
        }
        this.variableOpen = false;
        this.resetForm("formVariable");
      }
    },
  }
</script>

<style lang="scss" scoped>

</style>